<template>
  <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
    <!-- 权限是一颗树 -->
    <!-- 将数据绑定到组件上 -->
    <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
    <!-- id作为唯一标识 -->
    <el-tree
      ref="permTree"
      :data="permData"
      :props="defaultProps"
      :show-checkbox="true"
      :check-strictly="true"
      :default-expand-all="true"
      :default-checked-keys="selectCheck"
      node-key="id"
      @check="check"
    />
    <!-- 确定 取消 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
        <el-button size="small" @click="btnPermCancel">取消</el-button>
      </el-col>
    </el-row>
    {{ selectCheck }}
  </el-dialog>
</template>

<script>
import { getRoleDetails, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
export default {
  props: {
    showPermDialog: {
      type: Boolean,
      required: true
    },
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      defaultProps: {
        label: 'name'
      },
      permData: [], // 专门用来接收权限数据 树形数据
      selectCheck: [], // 定义一个数组来接收 已经选中的节点
      roleId: null // 用来记录分配角色的id
    }
  },
  async mounted() {
    // 钩子函数
    const res = await getPermissionList()
    this.permData = this.handleData(res, '0')
  },
  methods: {
    // 数形组件的 当复选框被点击的时候触发
    check(a, b) {
      this.selectCheck = b.checkedKeys
    },

    // 根据ID获取角色详情函数封装
    async getRoleDetails(id) {
      const { permIds } = await getRoleDetails(id)
      this.selectCheck = permIds
    },
    // 处理组织列表数据函数
    handleData(list, pID) {
      const arr = []
      list.forEach(v => {
        if (v.pid === pID) {
          const temp = this.handleData(list, v.id)
          v.children = temp
          arr.push(v)
        }
      })
      return arr
    },
    // 点击确定按钮
    async btnPermOK() {
      await assignPerm({ id: this.id, permIds: this.selectCheck })
      this.$message.success('分配成功')
      this.$emit('update:showPermDialog', false)
    },
    // 点击取消
    btnPermCancel() {
      this.selectCheck = [] // 重置数据
      this.$refs.permTree.setCheckedNodes([])
      this.$emit('update:showPermDialog', false)
    }
  }
}
</script>

<style lang='less' scoped>
</style>
